
import Vue from 'vue'

const findEle = (parent, type) => {
  return parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)
}

const trigger = (el, type) => {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}

Vue.directive('verify', {
  bind: function (el, binding) {
    // 正则规则可根据需求自定义
    const check = binding.value
    const $inp = findEle(el, 'input')
    el.$inp = $inp
    $inp.handle = function () {
      const val = $inp.value
      $inp.value = check(val)
      // console.log('val',val)
      trigger($inp, 'input')
    }
    $inp.addEventListener('blur', $inp.handle)
  },
  unmounted: function (el) {
    el.$inp.removeEventListener('blur', el.$inp.handle)
  },
})

